package com.yunyi.ne.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.DefaultHttpHeaders;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.websocketx.WebSocketClientHandshakerFactory;
import io.netty.handler.codec.http.websocketx.WebSocketVersion;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;

import java.net.URI;
import java.util.HashMap;
import java.util.Map;

public class NettyWebSocketClientFactory {

    private static final Map<String, NettyWebSocketClient> clients = new HashMap<>();
    private static final EventLoopGroup group = new NioEventLoopGroup();

    public static NettyWebSocketClient createClient(String serverUrl) throws Exception {
        if (clients.containsKey(serverUrl)) {
            return clients.get(serverUrl);
        }

        URI uri = new URI(serverUrl);
        String scheme = uri.getScheme() == null ? "http" : uri.getScheme();
        final boolean ssl = "wss".equals(scheme);
        final SslContext sslContext;
        if (ssl) {
            sslContext = SslContextBuilder.forClient()
                    .trustManager(InsecureTrustManagerFactory.INSTANCE)
                    .build();
        } else {
            sslContext = null;
        }

        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        if (sslContext != null) {
                            socketChannel.pipeline().addLast(sslContext.newHandler(socketChannel.alloc()));
                        }
                        socketChannel.pipeline()
                                .addLast(new HttpClientCodec())
                                .addLast(new HttpObjectAggregator(8192))
                                .addLast(new NettyWebSocketClientHandler(WebSocketClientHandshakerFactory.newHandshaker(
                                        uri, WebSocketVersion.V13, null, true, new DefaultHttpHeaders()
                                )));
                    }
                });

        ChannelFuture future = bootstrap.connect(uri.getHost(), uri.getPort()).sync();
        Channel channel = future.channel();

        NettyWebSocketClient client = new NettyWebSocketClient(channel, serverUrl);
        clients.put(serverUrl, client);

        return client;
    }

    public static void closeAllClients() throws InterruptedException {
        for (NettyWebSocketClient client : clients.values()) {
            client.close();
        }
        group.shutdownGracefully();
    }
}